const express = require('express');
const router = express.Router();
const article = require('../db/collection/article');


router.post('/', (req, res, next)=>{
    let data = req.body;
    if (!('openId' in data) || !('subscribeTimes' in data)) {
        res.send({
            code: 400,
            msg: "参数缺失"
        });
    }else{
        article.findOne({'openId' : data.openId}, (err, ret)=>{
            if (err){
                res.send({
                    code: 400,
                    msg: "服务端错误"
                });
            }else if (ret) {
                let times = ret.subscribeTimes + 1;
                article.updateOne({'openId' : data.openId}, {subscribeTimes: times}, (err, rett)=>{
                    if (err){
                        res.send({
                            code: 400,
                            msg: "服务端错误"
                        });
                    }else{
                        res.send({
                            code: 200,
                            msg: 'ok'
                        })
                    }
                })
            }else{
                article.insertMany(data, (err, doc)=>{
                    if (err){
                        res.send({
                            code: 400,
                            msg: "服务端错误"
                        });
                    }else{
                        res.send({
                            code: 200,
                            msg: 'ok'
                        })
                    }
                })
            }
        })
        
    }
});
module.exports = router;